use std::net::{
    TcpListener,
    TcpStream
};

use std::io::{prelude::*, BufReader};

fn crater_server() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();
        println!("Connection established!");

        handle_connection(stream);
    }
}

fn handle_connection(mut stream: TcpStream) {
    let buf_reader = BufReader::new(&mut stream);
    
    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| {
            match result {
                Ok(e) => {e},
                Err(e)=> String::from("")
            }
        })
        .take_while(|line| !line.is_empty())
        .collect();

        println!("Request: {:#?}", http_request);

    // 响应
    println!("resp pre");
    let resp_txt = "HTTP/1.1 200 OK \r\n Content-Length: 0\r\n onnection:close \r\n \r\n";
    let _ = stream.write(resp_txt.as_bytes());
    let _ = stream.flush();
    println!("resp end");

    let buf_reader = BufReader::new(&mut stream);
    
    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| {
            match result {
                Ok(e) => {
                    e
                },
                Err(e)=> String::from("")
            }
        })
        .take_while(|line| !line.is_empty())
        .collect();

        println!("Request: {:#?}", http_request);

   
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test() {
        crater_server();
    }
}